/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jpa.controllers;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entity.Courses;
import java.util.ArrayList;
import java.util.List;
import entity.Enrollment;
import entity.User;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import jpa.controllers.exceptions.IllegalOrphanException;
import jpa.controllers.exceptions.NonexistentEntityException;

/**
 *
 * @author atap
 */
public class UserJpaController implements Serializable {

    public UserJpaController() {
    }

    public UserJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("EducationXPU");

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(User user) {
        if (user.getCoursesList() == null) {
            user.setCoursesList(new ArrayList<Courses>());
        }
        if (user.getEnrollmentList() == null) {
            user.setEnrollmentList(new ArrayList<Enrollment>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Courses> attachedCoursesList = new ArrayList<Courses>();
            for (Courses coursesListCoursesToAttach : user.getCoursesList()) {
                coursesListCoursesToAttach = em.getReference(coursesListCoursesToAttach.getClass(), coursesListCoursesToAttach.getCourseId());
                attachedCoursesList.add(coursesListCoursesToAttach);
            }
            user.setCoursesList(attachedCoursesList);
            List<Enrollment> attachedEnrollmentList = new ArrayList<Enrollment>();
            for (Enrollment enrollmentListEnrollmentToAttach : user.getEnrollmentList()) {
                enrollmentListEnrollmentToAttach = em.getReference(enrollmentListEnrollmentToAttach.getClass(), enrollmentListEnrollmentToAttach.getId());
                attachedEnrollmentList.add(enrollmentListEnrollmentToAttach);
            }
            user.setEnrollmentList(attachedEnrollmentList);
            em.persist(user);
            for (Courses coursesListCourses : user.getCoursesList()) {
                User oldCreaterUserIdOfCoursesListCourses = coursesListCourses.getCreaterUserId();
                coursesListCourses.setCreaterUserId(user);
                coursesListCourses = em.merge(coursesListCourses);
                if (oldCreaterUserIdOfCoursesListCourses != null) {
                    oldCreaterUserIdOfCoursesListCourses.getCoursesList().remove(coursesListCourses);
                    oldCreaterUserIdOfCoursesListCourses = em.merge(oldCreaterUserIdOfCoursesListCourses);
                }
            }
            for (Enrollment enrollmentListEnrollment : user.getEnrollmentList()) {
                User oldUserIdOfEnrollmentListEnrollment = enrollmentListEnrollment.getUserId();
                enrollmentListEnrollment.setUserId(user);
                enrollmentListEnrollment = em.merge(enrollmentListEnrollment);
                if (oldUserIdOfEnrollmentListEnrollment != null) {
                    oldUserIdOfEnrollmentListEnrollment.getEnrollmentList().remove(enrollmentListEnrollment);
                    oldUserIdOfEnrollmentListEnrollment = em.merge(oldUserIdOfEnrollmentListEnrollment);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(User user) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            User persistentUser = em.find(User.class, user.getId());
            List<Courses> coursesListOld = persistentUser.getCoursesList();
            List<Courses> coursesListNew = user.getCoursesList();
            List<Enrollment> enrollmentListOld = persistentUser.getEnrollmentList();
            List<Enrollment> enrollmentListNew = user.getEnrollmentList();
            List<String> illegalOrphanMessages = null;
            for (Courses coursesListOldCourses : coursesListOld) {
                if (!coursesListNew.contains(coursesListOldCourses)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Courses " + coursesListOldCourses + " since its createrUserId field is not nullable.");
                }
            }
            for (Enrollment enrollmentListOldEnrollment : enrollmentListOld) {
                if (!enrollmentListNew.contains(enrollmentListOldEnrollment)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Enrollment " + enrollmentListOldEnrollment + " since its userId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Courses> attachedCoursesListNew = new ArrayList<Courses>();
            for (Courses coursesListNewCoursesToAttach : coursesListNew) {
                coursesListNewCoursesToAttach = em.getReference(coursesListNewCoursesToAttach.getClass(), coursesListNewCoursesToAttach.getCourseId());
                attachedCoursesListNew.add(coursesListNewCoursesToAttach);
            }
            coursesListNew = attachedCoursesListNew;
            user.setCoursesList(coursesListNew);
            List<Enrollment> attachedEnrollmentListNew = new ArrayList<Enrollment>();
            for (Enrollment enrollmentListNewEnrollmentToAttach : enrollmentListNew) {
                enrollmentListNewEnrollmentToAttach = em.getReference(enrollmentListNewEnrollmentToAttach.getClass(), enrollmentListNewEnrollmentToAttach.getId());
                attachedEnrollmentListNew.add(enrollmentListNewEnrollmentToAttach);
            }
            enrollmentListNew = attachedEnrollmentListNew;
            user.setEnrollmentList(enrollmentListNew);
            user = em.merge(user);
            for (Courses coursesListNewCourses : coursesListNew) {
                if (!coursesListOld.contains(coursesListNewCourses)) {
                    User oldCreaterUserIdOfCoursesListNewCourses = coursesListNewCourses.getCreaterUserId();
                    coursesListNewCourses.setCreaterUserId(user);
                    coursesListNewCourses = em.merge(coursesListNewCourses);
                    if (oldCreaterUserIdOfCoursesListNewCourses != null && !oldCreaterUserIdOfCoursesListNewCourses.equals(user)) {
                        oldCreaterUserIdOfCoursesListNewCourses.getCoursesList().remove(coursesListNewCourses);
                        oldCreaterUserIdOfCoursesListNewCourses = em.merge(oldCreaterUserIdOfCoursesListNewCourses);
                    }
                }
            }
            for (Enrollment enrollmentListNewEnrollment : enrollmentListNew) {
                if (!enrollmentListOld.contains(enrollmentListNewEnrollment)) {
                    User oldUserIdOfEnrollmentListNewEnrollment = enrollmentListNewEnrollment.getUserId();
                    enrollmentListNewEnrollment.setUserId(user);
                    enrollmentListNewEnrollment = em.merge(enrollmentListNewEnrollment);
                    if (oldUserIdOfEnrollmentListNewEnrollment != null && !oldUserIdOfEnrollmentListNewEnrollment.equals(user)) {
                        oldUserIdOfEnrollmentListNewEnrollment.getEnrollmentList().remove(enrollmentListNewEnrollment);
                        oldUserIdOfEnrollmentListNewEnrollment = em.merge(oldUserIdOfEnrollmentListNewEnrollment);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = user.getId();
                if (findUser(id) == null) {
                    throw new NonexistentEntityException("The user with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            User user;
            try {
                user = em.getReference(User.class, id);
                user.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The user with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Courses> coursesListOrphanCheck = user.getCoursesList();
            for (Courses coursesListOrphanCheckCourses : coursesListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This User (" + user + ") cannot be destroyed since the Courses " + coursesListOrphanCheckCourses + " in its coursesList field has a non-nullable createrUserId field.");
            }
            List<Enrollment> enrollmentListOrphanCheck = user.getEnrollmentList();
            for (Enrollment enrollmentListOrphanCheckEnrollment : enrollmentListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This User (" + user + ") cannot be destroyed since the Enrollment " + enrollmentListOrphanCheckEnrollment + " in its enrollmentList field has a non-nullable userId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(user);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }
    
    public User loginUser(String email, String password) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Query q = em.createNamedQuery("User.login");
            q.setParameter("email", email);
            q.setParameter("pass", password);
            
            User user = null; 
            List result = q.getResultList();
            if(result.size() == 1){
                user = (User)result.get(0);
                return user;
             }
            return null;
        }
        finally {
            if (em != null) {
                em.close();
            }
        }
    }
    
    public boolean authenticateUser(String email, String password, User entity) {
        return entity.getEmail().equals(email) && entity.getPassword().equals(password);
    }

    public List<User> findUserEntities() {
        return findUserEntities(true, -1, -1);
    }

    public List<User> findUserEntities(int maxResults, int firstResult) {
        return findUserEntities(false, maxResults, firstResult);
    }

    private List<User> findUserEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(User.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public User findUser(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(User.class, id);
        } finally {
            em.close();
        }
    }

    public int getUserCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<User> rt = cq.from(User.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
